﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace FastEasy.Common.Jwt
{
    public class JwtHelper
    {
        /// <summary>
        /// 生成Token
        /// </summary>
        public static string CreateJwtToken(TokenModel tokenModel)
        {
            //携带信息
            var claims = new List<Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Jti,tokenModel.Jti),//token唯一id
                new Claim(JwtRegisteredClaimNames.Iss,tokenModel.Iss),//发行人
                new Claim(JwtRegisteredClaimNames.Aud,tokenModel.Aud),//受众人
                //生效时间,一般就是当前时间,也可以延迟生效,例如1小时候后生效
                new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                //过期时间,token失效的时间,也就是有效期,这里设置的是1天有效期
                new Claim(JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds()}"),
                //自定义载体信息,这里存放的是用户姓名,还有角色等其他的信息可以存放,看是否需要,可以不加
                new Claim(ClaimTypes.Name,tokenModel.Name),
            };

            //密钥(32位字节=16字符)
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("zhanzhanghuaqwyehsydghuaqwyehsyd"));
            //密钥加密方式
            var code = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //生成token
            var jwt = new JwtSecurityToken(issuer: "", claims: claims, signingCredentials: code);
            var token = new JwtSecurityTokenHandler().WriteToken(jwt);
            return token;
        }
    }

    public class TokenModel
    {
        /// <summary>
        /// 发行人
        /// </summary>
        public string Iss { get; set; }

        /// <summary>
        /// 生效时间
        /// </summary>
        public string Nbf { get; set; }

        /// <summary>
        /// 过期时间
        /// </summary>
        public string Exp { get; set; }

        /// <summary>
        /// token唯一id,我会取用户的唯一ID
        /// </summary>
        public string Jti { get; set; }

        /// <summary>
        /// 受众人
        /// </summary>
        public string Aud { get; set; }

        /// <summary>
        /// 用户姓名
        /// </summary>
        public string Name { get; set; }
    }
}